from flask import Flask
from flask import request
from rediscluster import StrictRedisCluster

app = Flask(__name__)

startup_nodes = [
    {"host": "172.31.30.68", "port": 6001},
    {"host": "172.31.30.68", "port": 6002},
    {"host": "172.31.30.62", "port": 6001},
    {"host": "172.31.30.62", "port": 6002},
    {"host": "172.31.30.66", "port": 6001},
    {"host": "172.31.30.66", "port": 6002},
]

key = 'sdg_spider_proxy'
rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)


@app.route('/proxyv1_set')
def set_proxy():
    print(request.args)
    token = request.args.get('token')
    ip = request.args.get('ip')
    status = request.args.get('status')
    print(request.args)
    msg = ''
    if not token:
        msg = 'Hello World!'

    if token == 'sdg_token':
        if status == '1':
            rc.set(key, ip)
            msg = 'set success!'
        else:
            if rc.exists(key):
                rc.delete(key)
                msg = 'delete success'
    return msg


@app.route('/proxyv1_get')
def get_proxy():
    token = request.args.get('token')
    if not token:
        return 'Hello World!'

    if token == 'sdg_token':
        if not rc.exists(key):
            return 'key is not exist'
        return rc.get(key)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=10022, debug=True)
